package com.wennn.top.security.model;

import com.wennn.top.security.model.token.JwtRawAccessToken;
import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @description: 安全令牌和会话信息
 * @author: wennn
 * @date: 5/9/20 3:34 PM
 */
public class JwtAuthToken extends AbstractAuthenticationToken {

    private JwtRawAccessToken jwtRawAccessToken;

    private SessionContext sessionContext;

    @Getter
    private String username;
    @Getter
    private String password;

    /**
     * @description: 登陆的时候用户传递用户信息的
     * @author: wennn
     * @date: 5/10/20 10:23 AM
     */
    public JwtAuthToken(String username,String password){
        super(null);
        this.jwtRawAccessToken = null;
        this.username = username;
        this.password = password;
        this.sessionContext = new SessionContext();
        this.setAuthenticated(false); // 未认证的
    }

    /**
     * @description: 用于校验token是否有效的
     * @author: wennn
     * @date: 5/10/20 10:22 AM
     */
    public JwtAuthToken(JwtRawAccessToken unsaftToke){
        super(null);
        this.jwtRawAccessToken = unsaftToke;
        this.sessionContext = new SessionContext();
        this.setAuthenticated(false);
    }

    /**
     * @description:  建立权限后的构建
     * @author: wennn
     * @date: 5/10/20 10:22 AM
     */
    public JwtAuthToken(SessionUser sessionUser,JwtRawAccessToken jwtRawAccessToken, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.eraseCredentials();
        this.sessionContext = new SessionContext();
        this.sessionContext.setSessionUser(sessionUser);
        this.jwtRawAccessToken = jwtRawAccessToken;
        this.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return this.jwtRawAccessToken;
    }

    @Override
    public Object getPrincipal() {
        return this.sessionContext;
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
//        this.jwtRawAccessToken = null;
//        this.sessionContext = null;
    }
}
